﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QMenu *menu1=ui->menubar->addMenu("文件");
    QAction *act1=menu1->addAction(QIcon(":/1.png"),"打开");
    QAction *act2=menu1->addAction(QIcon(":/2.png"),"保存");
    QAction *act3=menu1->addAction(QIcon(":/3.png"),"另存为");
    QAction *act4=menu1->addAction(QIcon(":/4.png"),"退出");
    act1->setShortcut(QKeySequence(tr("Ctrl+o")));
    act2->setShortcut(QKeySequence(tr("Ctrl+s")));
    act3->setShortcut(QKeySequence(tr("Ctrl+Shift+s")));
    act4->setShortcut(QKeySequence(tr("Ctrl+shift+x")));
    connect(act1,&QAction::triggered,this,&MainWindow::on_action1_triggered);
    connect(act2,&QAction::triggered,this,&MainWindow::on_action2_triggered);
    connect(act3,&QAction::triggered,this,&MainWindow::on_action3_triggered);
    connect(act4,&QAction::triggered,this,&QMainWindow::close);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_action1_triggered()
{
    QString filename=QFileDialog::getOpenFileName(
                this,
                tr("打开文件"),
                "../",
                tr("File text(*.txt);;All files(*.*)")
                );
    if(!filename.isEmpty())
    {
        qDebug()<<QString("用户打开文件:%1").arg(filename);
        openfile=filename;
        QFile fp(filename);
        if(fp.open(QIODevice::ReadOnly|QIODevice::Text))
        {
            QTextStream out(&fp);
            out.setCodec("UTF-8");
            QString text=out.readAll();
            ui->plainTextEdit->setPlainText(text);
            fp.close();
        }
        else
        {
            qDebug("打开文件失败");
        }
    }
    else
    {
        qDebug("用户取消打开文件");
    }
}

void MainWindow::on_action2_triggered()
{
    QString text=ui->plainTextEdit->toPlainText();
    QFile fp(openfile);
    if(fp.open(QIODevice::WriteOnly|QIODevice::Truncate))
    {
        QTextStream in(&fp);
        in.setCodec("UTF-8");
        in<<text;
        fp.close();
        qDebug("保存成功");
    }
    else
    {
        qDebug("open error");
    }
}

void MainWindow::on_action3_triggered()
{
    QString savefile=QFileDialog::getSaveFileName(
                this,
                tr("另存为"),
                openfile,
                tr("文本文件(*.txt);;全部文件(*.*)")
                );
    if(!savefile.isEmpty())
    {
        qDebug()<<"另存为:"<<QFileInfo(savefile).fileName();
    }
    else
    {
        qDebug("取消另存为");
    }
}

